<?php
class database extends Admin {

    private $tab = array( 'optimize' => '数据优化', 'backup' => '数据备份', 'restore' => '数据恢复', 'sql' => '运行SQL' );

    public function index( $c, $a ) {
        $this->type = R( 'type', 'optimize' );
        $method = "{$a}_{$this->type}";
        $this->$method( $c, $a );
    }

    private function index_optimize( $c, $a ) {
        $tables = $this->get_tables();
        include $this->display( $c );
    }

    private function index_backup( $c, $a ) {
        $this->index_optimize( $c, $a );
    }

    private function index_restore( $c, $a ) {
        $list = glob( APP_PATH . "/content/backup/*.sql" );
        foreach ( $list as $k => $v ) {
            $backFiles[ $k ][ 'size' ] = filesize( $v );
            $backFiles[ $k ][ 'name' ] = basename( $v );
            $backFiles[ $k ][ 'time' ] = basename( $v, '.sql' );
        }
        krsort( $backFiles );
        include $this->display( $c );
    }

    private function index_sql( $c, $a, $type ) {
        include $this->display( $c );
    }

    // 删除备份文件
    public function del_backup() {
        $file = APP_PATH . "/content/backup/" . R( 'v' ) . '.sql';
        if ( !@is_readable( $file ) ) {
            $this->error( "非法删除备份文件 {$file}! " );
        }
        @unlink( $file );
        $this->success( '删除SQL备份成功!' );
    }

    // 从备份文件中恢复数据
    public function restore() {
        $sqlfile = APP_PATH . "/content/backup/" . R( 'v' ) . '.sql';
        if ( !@is_readable( $sqlfile ) ) {
            $this->error( "备份文件 {$sqlfile} 不存在!" );
        }
        $sqldump = file_get_contents( $sqlfile );
        $sql = explode( ";\n", $sqldump );
        array_pop( $sql );
        foreach ( $sql as $v ) {
            $this->model->runSql( $v );
        }
        $this->model->Cache()->update();
        $this->success( '恢复备份数据成功!' );
    }

    // 备份数据库
    public function backup() {
        $tables = explode( ',', R( 'in_id' ) );
        $sqldump = '';

        $path = APP_PATH . "/content/backup/";
        mkdirs( $path );

        if ( !is_writable_dir( $path ) ) {
            $this->error( "备份目录{$path}不可写!" );
        }

        $sqlfile = $path . time() . ".sql";

        foreach ( $tables as $table ) {
            $sql = $this->get_table_sql( $table );
            $sql = $sql ? "{$sql}\n\n" : '';
            $sqldump .= $sql;
        }
        file_put_contents( $sqlfile, $sqldump );
        chmod( $sqlfile, 0666 );
        $this->success( '备份数据成功!' );
    }

    // 优化数据库表
    public function optimize() {
        $tables = R( 'in_id' );
        $this->model->runSql( "OPTIMIZE TABLE {$tables}" );
        $this->success( '修复数据库表 {$tables} 成功!' );
    }

    // 更新全部缓存
    public function upcache() {
        $this->model->Cache()->update();
        rm( APP_TPL, false );
        $this->success( '更新缓存成功!' );
    }

    // 运行SQL语句
    public function run_sql() {
        $sql = R( 'sql' );
        $this->model->runSql( $sql );
        $this->success( ( "{$sql} 执行成功。影响行数:" . $this->model->affectedRows() ) );
    }

    // 返回所有表信息
    private function get_tables() {
        return $this->model->findSql( "SHOW TABLE STATUS FROM " . dbname );
    }

    // 把数据库表转换成SQL语句
    private function get_table_sql( $table ) {

        $sql = "DROP TABLE IF EXISTS `{$table}`;\n";

        $create = $this->model->findSql( "SHOW CREATE TABLE {$table}" );
        $sql .= $create[ 0 ][ 'Create Table' ] . ";\n\n";

        $rows = $this->model->findSql( "select * from `{$table}`" );
        if ( !$rows ) {
            return $sql;
        }

        $key = "`" . implode( '`,`', array_keys( $rows[ 0 ] ) ) . "`";
        $key = "INSERT INTO `{$table}` ( {$key} ) VALUES \n";

        $val = '';
        foreach ( $rows as $v ) {
            $vals = array_values( $v );
            $tmp = '';
            foreach ( $vals as $t ) {
                $tmp[ ] = $this->model->escape( $t );
            }
            $val .= "(" . implode( ",", $tmp ) . "),\n";
        }
        $val = rtrim( rtrim( $val, "\n" ), "," );
        $sql .= "{$key}{$val};";
        return $sql;
    }
}